﻿using System;
using System.Net;
using System.Text.RegularExpressions;
using iriska;
using jabber.client;
using jabber.connection;

namespace bashim
{
    public class Plugin : AbstractPlugin
    {
        private static string GetQuote(string quote)
        {
            quote = quote.Replace("<br />", "\r\n");
            quote = quote.Replace("<div>", "");
            quote = quote.Replace("<div class=\"text\">", "");
            quote = quote.Replace("&lt;", "<");
            quote = quote.Replace("&gt;", ">");
            quote = quote.Replace("&#039;", "'");
            quote = quote.Replace("&#39;", "'");
            quote = quote.Replace("&quot;", "\"");
            quote = quote.Replace("<br>", "\n");
            quote = quote.Replace("\n\n", "\n");

            return quote;
        }

        public override void Process(ConfMessage message, Room room)
        {
            if (string.Compare(message.Message, "!bash", true) == 0)
            {
                try
                {
                    WebClient client = new WebClient();
                    string msg = client.DownloadString("http://bash.im/random");

                    var regex =
                        new Regex(
                            "<div class=\"actions\">.*?class=\"rating\">(?<rating>[0-9]+).+?(?<number>#[0-9]+).+?</div>.*?<div class=\"text\">(?<text>.*?)</div>",
                            RegexOptions.Singleline);
                    var match = regex.Match(msg);
                    var rating = match.Groups["rating"].Value;
                    var number = match.Groups["number"].Value;
                    var text = match.Groups["text"].Value;

                    room.PublicMessage(string.Format("{0} ({1})\n{2}\n", number, rating, GetQuote(text)));
                }
                catch (WebException webException)
                {
                    room.PublicMessage("Ошибка подключения к bash.im");
                }
                catch (Exception exception)
                {
                    room.PublicMessage("Ошибка при парсинге страницы");
                }
            }
        }

        public override string PluginName()
        {
            return "bash.im plugin";
        }
    }
}